package com.tree.rw.demo.config;

import com.tree.rw.demo.bean.MyRoutingDatasource;
import com.tree.rw.demo.enums.DBTypeEnum;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName com.tree.rw.demo.config
 * <p>
 * 配置所有的数据源，同时需要配置自定义的Routing规则的数据源，
 * 即数据源总数=所有已经存在的数据源数量+自定义数据源数量
 * </p>
 * @Author tree
 * @Date 2019-06-02 13:49
 * @Version 1.0
 */
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.master")
    public DataSource masterDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.slave1")
    public DataSource slave1DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public DataSource myRoutingDataSource(@Qualifier("masterDataSource") DataSource masterDataSource,
                                          @Qualifier("slave1DataSource") DataSource slave1DataSource){

        Map<Object,Object> targetDS = new HashMap<>();
        targetDS.put(DBTypeEnum.MASTER,masterDataSource);
        targetDS.put(DBTypeEnum.SLAVE1,slave1DataSource);

        MyRoutingDatasource myRoutingDatasource = new MyRoutingDatasource();
        //设置默认DataSource
        myRoutingDatasource.setDefaultTargetDataSource(masterDataSource);
        //设置需要路由的Datasource集合
        myRoutingDatasource.setTargetDataSources(targetDS);

        return myRoutingDatasource;
    }


}
